package com.yungu.swift.order.utils;


import com.alibaba.dubbo.config.annotation.Reference;
import com.yungu.swift.assets.driver.model.dto.CarDto;
import com.yungu.swift.assets.driver.model.dto.DriverDto;
import com.yungu.swift.assets.driver.model.vo.DriverVo;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.assets.passenger.model.dto.PassengerDto;
import com.yungu.swift.assets.passenger.model.dto.PassengerEmergencyMemberDto;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.SpringContextHolder;
import com.yungu.swift.common.service.CommonSmsService;
import com.yungu.swift.lbs.service.ThirdPartyService;
import com.yungu.swift.order.config.NacosListener;
import com.yungu.swift.order.model.dto.OrderDetailDto;
import com.yungu.swift.order.model.dto.OrderDto;
import com.yungu.swift.order.model.dto.OrderFareDto;
import com.yungu.swift.order.model.vo.JsonOrderDetailVo;
import com.yungu.swift.utils.DateUtils;
import com.yungu.swift.utils.MapUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


/**
 * Created by cuixiuyin on 2019/6/4.
 * 在此类管理所有短信发送，便于维护
 */
@Slf4j
@Component
public class SendMessageUtils {

    private static CommonSmsService commonSmsService;
    private static DriverService driverService;

    @Reference
    public void setCommonSmsService(CommonSmsService commonSmsService) {
        SendMessageUtils.commonSmsService = commonSmsService;
    }

    @Reference
    public void setDriverService(DriverService driverService) {
        SendMessageUtils.driverService = driverService;
    }

    /**
     * 派单给乘客紧急联系人发送通知
     * 【签名】您的好友[手机号：@]正在使用@，车牌号为[@]，司机为[@]，点击可查看他（她）的行程动态@。客服电话：@。
     * 示例：【云谷出行】您的好友[手机号：15656561225]正在使用快车，车牌号为[闽D456123]，司机为[雷师傅]，
     * 点击可查看他（她）的行程动态tn.qwe.cn。客服电话：400-4121-4521。
     */
    public static void msgNoticeEmergencyMember(List<PassengerEmergencyMemberDto> listMember, int type,
                                                OrderDetailDto orderDetailDto, DriverDto driverDto, String plateNum) {
        String typeTripName = "";
        switch (type) {
            case 1:
                typeTripName = "出租车";
                break;
            case 2:
                typeTripName = "专车";
                break;
            case 3:
                typeTripName = "跨城拼车";
                break;
            case 4:
                typeTripName = "快车";
                break;
            default:
                break;
        }
        String url = NacosListener.SYS_CONFIG.getApiHost() + "/h5/agreement/common/trip/share?appid=" + orderDetailDto.getAppid() + "&orderuuid=" + orderDetailDto.getOrderUuid();
        ThirdPartyService thirdPartyService = SpringContextHolder.getBean(ThirdPartyService.class);
        ResponseData<String> responseData = thirdPartyService.getShortUrl(url);
        if (responseData.isSuccess() && StringUtils.isNotEmpty(responseData.getData())) {
            for (PassengerEmergencyMemberDto memberDto : listMember) {
                StringBuffer msgSb = new StringBuffer("您的好友[手机号：");
                msgSb.append(orderDetailDto.getActualPasMob()).append("]正在使用").append(typeTripName)
                        .append("，车牌号为[").append(plateNum)
                        .append("]，司机为[").append(driverDto.getName())
                        .append("]，点击可查看他（她）的行程动态").append(responseData.getData())
                        .append("。客服电话 ：")
                        .append(driverService.getDriverServiceTel(driverDto.getUuid(), driverDto.getCompanyUuid()).getData())
                        .append("。");
                commonSmsService.sendCommon(memberDto.getMemberMobile(), msgSb.toString(), orderDetailDto.getAppid());
            }
        }
    }

    /**
     * 派单给司机时发送的短信
     */
    public static void assignDriverSend(DriverDto driverDto, OrderDetailDto orderDetailDto, String mobile) {
        StringBuilder strBuilder = new StringBuilder("您收到")
                .append(CommonUtils.getTimeTodayOrTomorrow(orderDetailDto.getDeparTime()))
                .append("从").append(orderDetailDto.getOriginAddress()).append("出发的派单，联系电话：").append(mobile)
                .append("，请准时接驾；详询：")
                .append(driverService.getDriverServiceTel(driverDto.getUuid(), null).getData());
        commonSmsService.sendCommon(driverDto.getMobile(), strBuilder.toString(), driverDto.getAppid());
    }


    /**
     * 后台调整订单费用时发送的短信
     */
    public static void adjustFareSend(JsonOrderDetailVo bean, OrderFareDto orderFareDto, Double preTotalFare) {
        String serviceTel = driverService.getDriverServiceTel(bean.getActualDriverUuid(), null).getData();
        //发送短信给乘客
        String mobile = bean.getPassenger().getMobile();
        String pasMsg = "您的订单金额" + preTotalFare + "元已由后台修改为" + orderFareDto.getTotalFare() + "元，" +
                "修改原因：" + orderFareDto.getAdjustReason() + "；请及时支付，详情可查询：" + serviceTel;
        commonSmsService.sendCommon(mobile, pasMsg, bean.getAppid());
        //发送短信给司机
        String driMsg = "乘客尾号" + StringUtils.right(mobile, 4) + "的订单金额" + preTotalFare + "元已由后台修改为：" +
                orderFareDto.getTotalFare() + "元，修改原因：" + orderFareDto.getAdjustReason() + "，详情可查询：" + serviceTel;
        commonSmsService.sendCommon(bean.getDriver().getMobile(), driMsg, bean.getAppid());
    }

    /**
     * 改派（行程开始前）发送的短信
     */
    public static void assBeforeSend(PassengerDto passenger, DriverVo assDriver, OrderDetailDto orderDet, Date deparTime, String contact) {
        String driMsg, pasMsg;
        //预约、日租、半日租
        if (StringUtils.isEmpty(orderDet.getDestAddress())) {
            driMsg = "您已接单：乘客尾号［" + passenger.getMobile().substring(0, 4) + "］，［" + DateUtils.format(deparTime, "YYYY年MM月dd日 HH:mm") + "］从［" + orderDet.getOriginAddress() + "］出发，请准时接驾";
            pasMsg = "您" + DateUtils.format(deparTime, "YYYY年MM月dd日 HH:mm") + "从" + orderDet.getOriginAddress() + "出发的订单已经被改派给司机：" + assDriver.getName() + "，联系电话：" + contact;
        } else {
            driMsg = "您已接单：乘客尾号［" + passenger.getMobile().substring(0, 4) + "］，［" + DateUtils.format(deparTime, "YYYY年MM月dd日 HH:mm") + "］从［" + orderDet.getOriginAddress() + "］到［" + orderDet.getDestAddress() + "］，请准时接驾";
            pasMsg = "您" + DateUtils.format(deparTime, "YYYY年MM月dd日 HH:mm") + "从" + orderDet.getOriginAddress() + "到" + orderDet.getDestAddress() + "的订单已经被改派给司机：" + assDriver.getName() + "，联系电话：" + contact;
        }
        //发送短信给乘客
        commonSmsService.sendCommon(passenger.getMobile(), pasMsg, passenger.getAppid());
        //发送短信给司机
        commonSmsService.sendCommon(assDriver.getMobile(), driMsg, assDriver.getAppid());
    }

//    /**
//     * 司机催款发送的短信
//     */
//    public static void rushFareSend(PassengerDto passengerDto, OrderFareDto orderFareDto) {
//        String msg = "您有一个用车订单还未支付，共[" + orderFareDto.getTotalFare() + "]元，请尽快到应用内支付。";
//        commonSmsService.sendCommon(passengerDto.getMobile(), msg, passengerDto.getAppid());
//    }
    /**
     * 司机催款发送的短信
     */
    public static void rushFareSend(PassengerDto passengerDto, OrderFareDto orderFareDto) {
        log.info("这里是发动催单短信");
        log.info(passengerDto.getMobile());
        log.info(String.valueOf(orderFareDto.getTotalFare()));
        log.info(passengerDto.getAppid());
        String msg = "您有一个用车订单还未支付，共[" + orderFareDto.getTotalFare() + "]元，请尽快到应用内支付。";
        commonSmsService.sendAliCommon(passengerDto.getMobile(), String.valueOf(orderFareDto.getTotalFare()), passengerDto.getAppid(),"1");
    }

    /**
     * 出租车改派订单发送的短信
     */
    public static void upAssTaxiOrderSend(PassengerService passengerService, OrderDto orderDto, OrderDetailDto orderDetailDto) {
        String msg = "您有一笔订单被改派，请到应用内查看";
        PassengerDto passengerDto = getPassengerByUuid(passengerService, orderDto.getPassengerUuid());
        if (passengerDto == null) {
            passengerDto = getPassengerByMobile(passengerService, orderDetailDto.getActualPasMob());
        }
        commonSmsService.sendCommon(passengerDto.getMobile(), msg, orderDto.getAppid());
    }

    /*---------------------跨城拼车--------------------*/


    /**
     * 客服：收到订单
     * <p>
     * 接到新订单，乘客手机：@；路线：@；出发时间：@；用车人数：@；留言：@，请尽快安排司机！
     *
     * @param order
     * @param detail
     */
    public static void newOrder2Service(OrderDto order, OrderDetailDto detail) {
        // 跨城拼车客服
        String joinServiceTel = driverService.getDriverJoinServiceTel(order.getActualDriverUuid(), null).getData();
        StringBuilder msg = new StringBuilder("接到新订单，乘客手机：").append(detail.getActualPasMob())
                .append("；路线：").append(detail.getOriginAddress()).append("-").append(detail.getDestAddress())
                .append("；出发时间：").append(DateUtils.format(detail.getDeparTime()))
                .append("；用车人数：").append(order.getSeatNum())
                .append("；留言：").append((StringUtils.isEmpty(detail.getRemark()) ? "无" : detail.getRemark()))
                .append("，请尽快安排司机！");
        SmsTaskHelper.execute(new SmsTask(commonSmsService, joinServiceTel, msg.toString(), order.getAppid()));
    }

    /**
     * 乘客：后台下单
     * <p>
     * 后台下单：恭喜！您于出发时间：@的订单，我们已确认预约成功，司机将准时接驾。我们将最晚出发前1小时~30分钟，给您发送司机信息。
     *
     * @param deparTime
     * @param mobile
     * @param appid
     */
    public static void joinOrderConfirm2Pas(Date deparTime, String mobile, String appid) {
        StringBuilder msg = new StringBuilder();
        msg.append("您的订单已确认预约成功！我们将尽快给您发送司机信息。");
        SmsTaskHelper.execute(new SmsTask(commonSmsService, mobile, msg.toString(), appid));
    }

    /**
     * 司机：收到派单（或改派）
     * <p>
     * 收到派单：乘客手机：@；路线：@；出发时间：@；用车人数：@；留言：@，请准时接驾！
     * 收到改派订单：乘客手机：@；路线：@；出发时间：@；用车人数：@；留言：@，请准时接驾！
     *
     * @param order
     * @param detail
     * @param mobile
     */
    public static void msgAssignedByJoinOrderDri(OrderDto order, OrderDetailDto detail, String mobile) {
        StringBuilder msg = new StringBuilder();
        if (null != order.getAssignDriverUuid()) {
            msg.append("收到改派订单：");
        } else {
            msg.append("收到派单：");
        }
        msg.append("乘客手机：" + detail.getActualPasMob() + "；路线：" + detail.getOriginAddress() + "-" + detail.getDestAddress() + "；出发时间：" + DateUtils.format(detail.getDeparTime()) + "；用车人数：" + order.getSeatNum() + "；留言：" + (StringUtils.isEmpty(detail.getRemark()) ? "无" : detail.getRemark()) + "，请准时接驾！");
        SmsTaskHelper.execute(new SmsTask(commonSmsService, mobile, msg.toString(), order.getAppid()));
    }

    /**
     * 司机：订单被改派
     *
     * @param detail
     * @param mobile
     * @param appid
     */
    public static void msgChangeAssignedByJoinOrderOldDri(OrderDetailDto detail, String mobile, String appid) {
        StringBuilder msg = new StringBuilder();
        msg.append("订单被改派通知！出发时间：").append(DateUtils.format(detail.getDeparTime()));
        msg.append(" 从" + detail.getOriginAddress() + "到" + detail.getDestAddress() + " 共" + detail.getActualPasNum() + "人，");
        msg.append("乘客手机号：" + detail.getActualPasMob()).append(" ");
        msg.append("请及时注意调整行程，造成不便敬请谅解！");
        SmsTaskHelper.execute(new SmsTask(commonSmsService, mobile, msg.toString(), appid));
    }

    /**
     * 乘客：派单成功通知
     * <p>
     * 正常派单：派单成功！您于出发时间：@的订单已经安排好了，司机手机：@；姓名：@；车牌号：@，请及时做好出发准备！
     *
     * @param detail
     * @param driverMobile
     * @param car
     * @param mobile
     */
    public static void msgAssignedByJoinOrderPas(OrderDetailDto detail, String driverMobile, CarDto car, String mobile) {
        StringBuilder msg = new StringBuilder()
                .append("派单成功！您于出发时间：").append(DateUtils.format(detail.getDeparTime()))
                .append("的订单已经安排好了，司机手机：").append(driverMobile)
                .append("；车牌号：").append(car.getPlateNum())
                .append("，请及时做好出发准备！");
        SmsTaskHelper.execute(new SmsTask(commonSmsService, mobile, msg.toString(), detail.getAppid()));
    }

    /**
     * 乘客：订单改派通知
     * <p>
     * 改派：请注意，您于出发时间：@的订单，因为特殊原因改派给了新的司机，司机手机：@；姓名：@；车牌号：@，请及时做好出发准备！
     *
     * @param detail
     * @param driverMobile
     * @param plateNum
     * @param mobile
     */
    public static void msgChangeAssignedByJoinOrderPas(OrderDetailDto detail, String driverMobile, String plateNum, String mobile) {
        StringBuilder msg = new StringBuilder();
        msg.append("请注意，您用车时间：").append(DateUtils.format(detail.getDeparTime())).append("的订单，因为特殊原因改派给了新的司机，司机手机：").append(driverMobile).append("；车牌号：").append(plateNum).append("，请及时做好准备！");
        SmsTaskHelper.execute(new SmsTask(commonSmsService, mobile, msg.toString(), detail.getAppid()));
    }

    /**
     * 乘客：预约中通知
     *
     * @param deparTime
     * @param mobile
     * @param appid
     */
    public static void msgJoinOrderSubing(Date deparTime, String mobile, String appid) {
        StringBuilder msg = new StringBuilder();
        msg.append("尊敬的乘客，您于出发时间：" + DateUtils.format(deparTime) + "的订单已提交成功。我们将在30分钟内尽快确认订单，请您耐心等待。");
        SmsTaskHelper.execute(new SmsTask(commonSmsService, mobile, msg.toString(), appid));
    }

    /**
     * 跨城拼车：关闭订单短信推送
     *
     * @param mobile
     * @param msgContent
     * @param appid
     */
    public static void closeJoinOrder(String mobile, String msgContent, String appid) {
        SmsTaskHelper.execute(new SmsTask(commonSmsService, mobile, msgContent, appid));
    }

    /**
     * 通用发送
     *
     * @param mobile
     * @param msgContent
     * @param appid
     */
    public static void generalSend(String mobile, String msgContent, String appid) {
        SmsTaskHelper.execute(new SmsTask(commonSmsService, mobile, msgContent, appid));
    }

    /*---------------------跨城拼车相关短信推送（结束）---------------------*/


    private static PassengerDto getPassengerByUuid(PassengerService passengerService, String uuid) {
        return passengerService.get(uuid).getData();
    }

    private static PassengerDto getPassengerByMobile(PassengerService passengerService, String mobile) {
        return passengerService.get(MapUtils.build("mobile", mobile)).getData();
    }
}
